using Adnc.Application.Shared.WeChat;
using Adnc.Shared.RpcServices.Services;
using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WYT.Usr.Application.EventSubscribers;

namespace WYT.Usr.WebApi
{
    public class Startup
    {
        private readonly IHostEnvironment _environment;

        private  IServiceCollection _services;

        private readonly IConfiguration _config;


        public Startup(IHostEnvironment environment, IConfiguration config)
        {
            _environment = environment;
            _config = config;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            _services = services;
            services.AddWYTServices(registion => {
                var policies = registion.GenerateDefaultRefitPolicies();
#if DEBUG
                registion.AddRpcService<IOrdersRpcService>("https://gateway.wyuntao.com", policies);
                registion.AddRpcService<ISysRpcService>("https://gateway.wyuntao.com", policies);
                registion.AddRpcService<IProductRPCService>("https://gateway.wyuntao.com", policies);
                registion.AddRpcService<IPayRpcService>("https://gateway.wyuntao.com", policies);
                registion.AddEventBusSubscribers();
#else
                registion.AddRpcService<IOrdersRpcService>("wyt.ord.webapi", policies);
                registion.AddRpcService<ISysRpcService>("wyt.sys.webapi", policies);
                registion.AddRpcService<IProductRPCService>("wyt.pro.webapi", policies);
                registion.AddRpcService<IPayRpcService>("wyt.pay.webapi", policies);
                registion.AddEventBusSubscribers<CapEventSubscriber>();
#endif
            });
            services.AddWeChatServices();
        }

        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterAdncModules(_services);
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseAdncMiddlewares();
            if (_environment.IsProduction() || _environment.IsStaging())
            {
                app.RegisterToConsul();
            }
        }
    }
}
